package com.fosss.band.service.impl;

import com.fosss.band.constant.FollowType;
import com.fosss.band.entity.Album;
import com.fosss.band.entity.Band;
import com.fosss.band.entity.Follow;
import com.fosss.band.entity.Score;
import com.fosss.band.entity.vo.AlbumQueryVo;
import com.fosss.band.entity.vo.AlbumVo;
import com.fosss.band.mapper.AlbumMapper;
import com.fosss.band.mapper.BandMapper;
import com.fosss.band.mapper.FollowMapper;
import com.fosss.band.service.AlbumService;
import com.fosss.band.service.ScoreService;
import com.fosss.band.utils.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.fosss.band.utils.ResultCodeEnum.MESSAGE_UN_ENOUGH;
import static com.fosss.band.utils.ResultCodeEnum.SCORE_REPEAT;

/**
 * @author: fosss
 * Date: 2023/12/27
 * Time: 20:36
 * Description:
 */
@Service
public class AlbumServiceImpl implements AlbumService {

    @Resource
    private AlbumMapper albumMapper;
    @Resource
    private ScoreService scoreService;
    @Resource
    private BandMapper bandMapper;
    @Resource
    private FollowMapper followMapper;

    /**
     * 分页条件查询
     */
    @Override
    public Result getAlbumListPage(Integer userId, Integer page, Integer size, AlbumQueryVo albumQueryVo) {
        //开启分页
        PageHelper.startPage(page, size);
        List<Album> list = albumMapper.pageQuery(albumQueryVo);
        List<AlbumVo> collect = list.stream().map(album -> {
            AlbumVo albumVo = new AlbumVo();
            BeanUtils.copyProperties(album, albumVo);
            Band band = bandMapper.selectById(albumVo.getBandId());
            albumVo.setBandName(band.getName());
            //查询是否关注
            Follow follow = followMapper.select(userId, FollowType.FOLLOW_TYPE_ALBUM, album.getId());
            albumVo.setFollowed(follow != null);
            return albumVo;
        }).collect(Collectors.toList());

        PageInfo<AlbumVo> pageInfo = new PageInfo<>(collect);
        return Result.ok().data("rows", pageInfo.getList()).data("total", pageInfo.getTotal());
    }

    /**
     * 删除专辑
     */
    @Override
    public Result delete(Integer id) {
        albumMapper.deleteById(id);
        return Result.ok();
    }

    /**
     * 添加专辑
     */
    @Override
    public Result addAlbum(Album album) {
        if (StringUtils.isEmpty(album.getName()) || StringUtils.isEmpty(album.getDescription()) || album.getScore() == null
                || album.getBandId() == null) {
            return Result.error().code(MESSAGE_UN_ENOUGH.getCode()).message(MESSAGE_UN_ENOUGH.getMessage());
        }
        //设置发布时间
        album.setCreateTime(new Date());
        albumMapper.add(album);
        return Result.ok();
    }

    /**
     * 根据id查询专辑
     */
    @Override
    public Result getAlbum(Integer id) {
        Album album = albumMapper.getById(id);
        AlbumVo albumVo = new AlbumVo();
        BeanUtils.copyProperties(album, albumVo);
        //查询乐队名

        return Result.ok().data("row", album);
    }

    /**
     * 更新专辑
     */
    @Override
    public Result update(Album album) {
        if (StringUtils.isEmpty(album.getName()) || StringUtils.isEmpty(album.getDescription()) || album.getScore() == null
                || album.getBandId() == null) {
            return Result.error().code(MESSAGE_UN_ENOUGH.getCode()).message(MESSAGE_UN_ENOUGH.getMessage());
        }
        albumMapper.updateById(album);
        return Result.ok();
    }

    /**
     * 给专辑打分
     */
    @Transactional
    @Override
    public Result scoring(Score score) {
        //检查是否打过分
        Score s = scoreService.getByFanIdAndAlbumId(score.getFanId(), score.getAlbumId());
        if (s != null) {
            //该用户已经打过一次分了
            return Result.error().code(SCORE_REPEAT.getCode()).message(SCORE_REPEAT.getMessage());
        }
        //添加打分记录
        scoreService.addScore(score);
        //修改专辑评分
        Album album = albumMapper.getById(score.getAlbumId());
        Float initialScoring = album.getScore();
        Integer userScoring = score.getScore();
        float nowScore = calculateNowScore(initialScoring, userScoring);
        album.setScore(nowScore);
        albumMapper.updateById(album);
        return Result.ok();
    }


    /**
     * 获取加权平均分
     */
    private float calculateNowScore(float score, float u_score) {
        double weight = 0.2; // 假设用户评分占20%权重
        double result = (score * (1 - weight)) + (u_score * weight);
        DecimalFormat df = new DecimalFormat("#.#"); // 保留一位小数
        String resultString = df.format(result); // 格式化为字符串
        return Float.parseFloat(resultString); // 将字符串转换为浮点数
    }

    /**
     * 批量查询专辑信息
     */
    @Override
    public List<AlbumVo> getAlbumVoByIds(List<Integer> ids) {
        //查询专辑列表
        List<Album> albumList = albumMapper.selectAlbums(ids);
        //封装所需数据
        List<AlbumVo> collect = albumList.stream().map(album -> {
            AlbumVo albumVo = new AlbumVo();
            BeanUtils.copyProperties(album, albumVo);
            //设置乐队名
            Band band = bandMapper.selectById(album.getBandId());
            albumVo.setBandName(band.getName());
            return albumVo;
        }).collect(Collectors.toList());

        return collect;
    }
}








